<?php
function get_ingredients(){
$query = "SELECT * FROM ing";
$qid = mysql_query($query);
$ingredients = array();
    while($row= mysql_fetch_object($qid)) {
        array_push($ingredients, $row);
    }
    return $ingredients;
}

function ingredient_exist($in){
  $exist = FALSE;
  $array = get_ingredients();
  foreach($array as $val){
    if(strtolower($in) ==strtolower($val->ing_name)){
      $exist = $val -> ing_id;
    }
  }
  return $exist;
}

function create_ingredient($ing){
  $exist = ingredient_exist($ing);
  
  if(!$exist){
    $query = sprintf("INSERT INTO  `ing` ( `ing_id` , `ing_name` ) VALUES ( NULL , '%s')", $ing);
    $result = mysql_query($query);
    if (!$result) {
      die('Invalid query: ' . mysql_error());
    }
    return mysql_insert_id();
  } else 
   return $exist;
  
}

function print_ingredients($rid){
    $array = array();
    $query = "SELECT ing.*, ing_lk.ing_q, ing_lk.unit_id, ing_lk.mod_id, modifier.mod_name, unit.unit_s, unit.unit_p FROM recipe, ing, ing_lk, unit, modifier WHERE ing_lk.r_id = recipe.r_id AND ing_lk.ing_id = ing.ing_id AND ing_lk.unit_id = unit.unit_id AND ing_lk.mod_id = modifier.mod_id ";
    $query .= sprintf("AND recipe.r_id = %d", $rid);

    $qid = mysql_query($query);

    while($row= mysql_fetch_object($qid)) {
        array_push($array, $row);
    }
    return $array;
}
?>